﻿using AutoMapper;
using BasicInformation.ApiWrite.Application.Command.Unit;
using BasicInformation.Domain;
using BasicInformation.ErrorCode;
using BasicInformation.Infrastructure.Implement;
using MediatR;

namespace BasicInformation.ApiWrite.Application.Handler.Unit
{
    public class AddUnitHandler : IRequestHandler<AddUnitCommand, ApiResult<int>>
    {
        private readonly DatabaseContext db;
        private readonly IMapper mapper;
        private readonly ILogger<AddUnitHandler> logger;

        public AddUnitHandler(DatabaseContext db,IMapper mapper,ILogger<AddUnitHandler> logger)
        {
            this.db = db;
            this.mapper = mapper;
            this.logger = logger;
        }
        public async Task<ApiResult<int>> Handle(AddUnitCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            var unit=mapper.Map<UnitModel>(request);
            var model=db.SqlSugar.Queryable<UnitModel>().Where(x=>x.UnitCode==request.UnitCode&&x.UnitName==request.UnitName).First();
            if (model != null)
            {
                result.Msg = "单元管理已存在，请重新输入";
                result.Code = ApiEnum.Fail;
                logger.LogError(result.Msg);
                return await Task.FromResult(result);
            }
            int r=await db.SqlSugar.Insertable(unit).ExecuteCommandAsync();
            if (r > 0)
            {
                result.Msg = "单位管理添加成功";
                result.Data = r;
                result.Code = ApiEnum.OK;
                logger.LogInformation(result.Msg);
            }
            else
            {
                result.Msg = "单位管理添加失败";
                result.Data = r;
                result.Code = ApiEnum.Fail;
                logger.LogError(result.Msg);
            }
            return await Task.FromResult(result);
        }
    }
}
